package com.cehome.cloudbox.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.cehome.cloudbox.constans.ExtensionTaskProperties;
import com.cehome.cloudbox.service.IProcCommonService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.MultiInstanceLoopCharacteristics;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

/**
 * 全局的任务创建监听
 * @author zfl
 */
@Component
@Slf4j
public class GlobalTaskCreateListener extends AbstractFlowableEngineEventListener {

    @Resource
    protected RepositoryService repositoryService;
    @Resource
    private IProcCommonService iProcCommonService;

    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        // 得到任务实例
        FlowableEntityEventImpl eventImpl = (FlowableEntityEventImpl) event;
        TaskEntity taskEntity = (TaskEntity) eventImpl.getEntity();
        log.info("任务创建开始，taskId：{}", taskEntity.getId());

        // 获取申请节点
        String applyDefinitionId = Convert.toStr(taskEntity.getVariable(ExtensionTaskProperties.FLOWABLE_APPLY_DEFINITION_ID));
        // 获取申请人
        String applyUserId = Convert.toStr(taskEntity.getVariable(ExtensionTaskProperties.FLOWABLE_APPLY_USER_ID));

        // 当前节点为申请节点时
        if (taskEntity.getTaskDefinitionKey().equals(applyDefinitionId)) {
            // 设置候选人
            taskEntity.addCandidateUser(applyUserId);
        } else {
            // 获取节点信息
            BpmnModel bpmnModel = repositoryService.getBpmnModel(event.getProcessDefinitionId());
            FlowElement flowElement = bpmnModel.getFlowElement(taskEntity.getTaskDefinitionKey());
            UserTask userTask = (UserTask) flowElement;
            MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = userTask.getLoopCharacteristics();
            // 会签时不做处理
            if (ObjectUtil.isNotEmpty(multiInstanceLoopCharacteristics)) {
                return;
            }
            // 候选人数据
            String taskCandidateData = flowElement.getAttributeValue(ExtensionTaskProperties.NAMESPACE_URI, ExtensionTaskProperties.TASK_CANDIDATE_DATA);
            // 获取候选人IDList
            List<String> userIdList = iProcCommonService.getUserIdList(taskCandidateData, applyUserId);
            log.info("候选人用户ID：{}", userIdList);
            // 设置候选人
            if (ObjectUtil.isNotEmpty(userIdList)) {
                taskEntity.addCandidateUsers(userIdList);
            }
        }
    }

}
